//兑换审批
let $productExchangeDetailsTable = $("#productExchangeDetailsTable");
let $exchangeDetailsTable = $("#exchangeDetailsTable");
let examineFilePath;
let exchangeTableData=[];
//防止表头与表格不对齐
$(window).resize(function () {
    $exchangeDetailsTable.bootstrapTable('resetView');
    $productExchangeDetailsTable.bootstrapTable('resetView');
    $("#exchangeTable").bootstrapTable('resetView');
});

$(function () {
    //产品兑换审批列表
    productExchangeDetailsList()
    //会员权益兑换审批列表
    exchangeDetailsList()
    $('.datepicker').datepicker({
        language: "zh-CN",
        autoclose: true, //选择后自动关闭
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });
    $('#arriveTimeStart').on('changeDate',function(){
        var startDate = $('#arriveTimeStart').val();
        var endDate = $('#arriveTimeEnd').val();
        if (endDate < startDate) {  // 对比结束日期和新的起止日期，起止日期大于结束日期则清空结束日期
            $('#arriveTimeEnd').val('');
        }
        $('#arriveTimeEnd').datepicker('destroy').datepicker({
            language: "zh-CN",
            autoclose: true, //选择后自动关闭
            clearBtn: true,
            todayHighlight: true,
            format: "yyyy-mm-dd",
            startDate: new Date(startDate)
        });
    });
})


//兑换明细页面下的方法
//产品兑换审批列表
function productExchangeDetailsList() {
    $productExchangeDetailsTable.bootstrapTable('destroy');//先销毁表格
    $productExchangeDetailsTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/csd/productManager/selectProductExchangeApprovalList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        height:820,
        dataType: "json",//数据类型F
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'customerId',
        idField: 'customerId',
        pageSize: 20,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: [20, 50],//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedRightNumber: 1,    // 右侧固定列
        queryParams: productExchangeDetailParams,//查询参数
        columns: [
            {title: '所属订单', field: 'orderNumber', align: 'left', valign: 'middle',formatter: orderNumberFormat},
            {title: '所属分公司', field: 'companyName', align: 'left', valign: 'middle'},
            {title: '所属人', field: 'userName', align: 'left', valign: 'middle'},
            {title: '审核状态', field: 'approvalStatus', align: 'left', valign: 'middle',formatter: approvalStatusFormat},
            {title: '审核人', field: 'approverName', align: 'left', valign: 'middle'},
            {title: '操作', field: 'operate', align: 'right',events: operateEvents,formatter:productExchangeDetailgenderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {

        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        }
    });
}
//产品兑换明细参数
function productExchangeDetailParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //搜索条件
    return params;
}
/**
 * 自定义操作列内容
 */
function productExchangeDetailgenderOpt(value, row, index) {
    if(row.approvalStatus=='1'){
        var html = '<button type="button" class="btn-default activeBtn approvalBtn" id="productApproval">审核</button>';
    }else{
        var html = '<button type="button" class="btn-default activeBtn approvalBtn" id="productDetail">查看</button>';
    }
    return html;
}
//审核状态
function approvalStatusFormat(value, row, index) {
    let approvalStatus;
    switch(row.approvalStatus){
        case '0':
            approvalStatus='通过';
            break;
        case '1':
            approvalStatus='待审批';
            break;
        case '2':
            approvalStatus='不通过';
            break;
    }
    return approvalStatus;
}
//会员权益兑换审批列表
function exchangeDetailsList() {
    closeFilterContainer();//关闭高级筛选
    $exchangeDetailsTable.bootstrapTable('destroy');//先销毁表格
    $exchangeDetailsTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/csd/productManager/selectChangeCourseCecordList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        height:820,
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'customerId',
        idField: 'customerId',
        pageSize: 20,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: [20, 50],//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedRightNumber: 1,    // 右侧固定列
        queryParams: exchangeDetailParams,//查询参数
        columns: [
            // {title: '兑换前产品', field: 'finishProductName', align: 'left', valign: 'middle'},
            // {title: '兑换后产品', field: 'changeCourseTitle', align: 'left', valign: 'middle'},
            {title: '所属订单', field: 'orderNumber', align: 'left', valign: 'middle',formatter: orderNumberFormat},
            {title: '所属合同', field: 'contractNumber', align: 'left', valign: 'middle',formatter: contractNumberFormat},
            {title: '会员卡卡号', field: 'memberCardNumber', align: 'left', valign: 'middle',formatter: customerCardDetail},
            {title: '兑换规则标题', field: 'ruleTitle', align: 'left', valign: 'middle'},
            {title: '所属分公司', field: 'companyName', align: 'left', valign: 'middle'},
            {title: '所属人', field: 'userName', align: 'left', valign: 'middle'},
            {title: '兑换时间', field: 'createTm', align: 'left', valign: 'middle'},
            {title: '操作', field: 'operate', align: 'right',events: operateEvents,formatter:exchangeDetailgenderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {

        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        }
    });
}
//兑换明细参数
function exchangeDetailParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //搜索条件
    // params.dateType = $("#dateType").val();//全部
    params.startDate = $.trim($('#arriveTimeStart').val());//开始日期
    params.endDate= $.trim($('#arriveTimeEnd').val());//截止日期
    params.ruleTitle = $("#ruleTitle").val()
    return params;
}
/**
 * 自定义操作列内容
 */
function exchangeDetailgenderOpt(value, row, index) {
    let html = '<button type="button" class="btn-default activeBtn approvalBtn" id="approval">审核</button>';
    return html;
}
/*对象拼接参数*/
function splicingParams(obj){
    var paramsStr='';
    for(var key in obj){
        paramsStr+=(key+"="+obj[key])+'&'
    }
    return paramsStr.substring(0,paramsStr.lastIndexOf('&'))
}
//审批点击事件
let changeCourseId,changeCourseTypeNum;
window.operateEvents = {
    'click #productDetail': function (e, value, row, index){
        openTab('产品兑换审核','/front/messageManager/productExchangeReview?type=readonly&'+splicingParams(row));
    },
    //点击事件
    'click #productApproval': function (e, value, row, index){
        openTab('产品兑换审核','/front/messageManager/productExchangeReview?type=edit&'+splicingParams(row));
    },
    'click #approval': function (e, value, row, index){
         $("#approvalModal").modal('show');
         changeCourseId = row.changeCourseId;
         changeCourseTypeNum = row.changeCourseType;
        $("#ruleTitleText").text(row.ruleTitle);
         $("#userName").text(row.userName);
         $("#companyName").text(row.companyName);
        $("#memberCardNumber").text(row.memberCardNumber);
         // $("#ruleNumber ").text(row.ruleNumber);
        examineFilePath = row.img;
        $("#exchangeTableContainer").hide();
         let changeCourseType;
         if(row.changeCourseType==0){
             changeCourseType='现场参会';
         }else if(row.changeCourseType==1){
             changeCourseType='行业会';
         }else if(row.changeCourseType==2){
             changeCourseType='高端班';
             $("#exchangeTableContainer").show();
             setTimeout(function(){
                 exchangeTableList();
             },100)
         }else if(row.changeCourseType==3){
             changeCourseType='高端班兑换现场天数';
         }else if(row.changeCourseType==4){
             changeCourseType='现场天数兑换行业会次数';
         }else if(row.changeCourseType==5){
             changeCourseType='行业会次数兑换现场天数';
         }
         $("#changeCourseType").text(changeCourseType);
         //清除已有校验
         var bootstrapValidator = $("#approvalForm").data('bootstrapValidator');
         if (bootstrapValidator) {
            $("#approvalForm").data('bootstrapValidator').destroy();
            $('#approvalForm').data('bootstrapValidator', null);
         }
         $("#remarks").val("");
         $("input[name='approvalResult']:checked").prop('checked',false);
         approvalValidator()
    }
};
function exchangeTableParams(params){
    //搜索条件
    params.changeCourseId = changeCourseId;
    return params;
}
function exchangeTableList() {
    $("#exchangeTable").bootstrapTable('destroy');//先销毁表格
    $("#exchangeTable").bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/csd/productManager/selectExamineAndApproveList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        height:380,
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "client",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'customerId',
        idField: 'customerId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: [5,10,15],//可供选择的每页的行数
        // fixedColumns: true,     // 冻结列
        // fixedRightNumber: 1,    // 右侧固定列
        queryParams: exchangeTableParams,//查询参数
        columns: [
            {title: '兑换前产品', field: 'finishProductName', align: 'left', valign: 'middle'},
            {title: '兑换后产品', field: 'changeCourseTitle', align: 'left', valign: 'middle'},
            {title: '所属订单', field: 'orderNumber', align: 'left', valign: 'middle',width: '120',formatter: orderNumberFormat},
            {title: '所属合同', field: 'contractNumber', align: 'left', valign: 'middle',width: '120',formatter: contractNumberFormat},
            // {title: '兑换规则编码', field: 'ruleNumber', align: 'left', valign: 'middle',width: '120'},
            {title: '所属分公司', field: 'companyName', align: 'left', valign: 'middle'},
            {title: '所属人', field: 'userName', align: 'left', valign: 'middle', width: '100'},
            {title: '兑换时间', field: 'createTm', align: 'left', valign: 'middle', width: '100'}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            exchangeTableData=obj['rows'];
            return obj;
        },
        onLoadSuccess: function () {

        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        }
    });
}
function getStr(data,fileName){
    var arr=[];
    data.filter((item) =>{
        arr.push(item[fileName])
    });
    return arr.join()
}
/**
 * 全部/今天/周/月/上月/自定义切换
 * @param time
 */
function selectTime(time) {
    $('.timeBtn').removeClass('active-second');
    $(`#${time}`).addClass('active-second');
    if(time==='customize'){
        //自定义
        $("#dateType").val("");
        if($('#customInput').is(":hidden")){
            $('#customInput').show();
        }else{
            $('#customInput').hide();
        }
    }else{
        //全部
        $('#customInput').hide();
        $('#arriveTimeStart').val('');
        $('#arriveTimeEnd').val('');
        $("#dateType").val("");
        exchangeDetailsList();
    }

}
//打开高级筛选弹框
function openFilterContainer(){
    $("#closeFilter").show();
    $("#openFilter").hide();
    $("#filterFilesContainer").slideDown();
}
//关闭高级筛选弹框
function closeFilterContainer(){
    $("#openFilter").show();
    $("#closeFilter").hide();
    $("#filterFilesContainer").slideUp();
}
//点击高级筛选切换显示隐藏
function showToggle(){
    if($("#filterFilesContainer").is(":hidden")){
        openFilterContainer()
    }else{
        closeFilterContainer()
    }
}
/*function productApprovalValidator(){
    $('#productApprovalForm').bootstrapValidator({
        fields: {
            productRemarks: {
                validators: {
                    notEmpty: {
                        message: '备注不能为空'
                    }
                }
            },
            productApprovalResult:{
                validators: {
                    notEmpty: {
                        message: '审批结果不能为空'
                    }
                }
            }
        }
    })
}*/
 function approvalValidator(){
     $('#approvalForm').bootstrapValidator({
         fields: {
             remarks: {
                 validators: {
                     notEmpty: {
                         message: '备注不能为空'
                     }
                 }
             },
             approvalResult:{
                 validators: {
                     notEmpty: {
                         message: '审批结果不能为空'
                     }
                 }
             }
         }
     })
 }
 //提交审核
function submitApproval(){
    // 验证表单
    var bootstrapValidator = $("#approvalForm").data('bootstrapValidator');
    bootstrapValidator.validate();
    if (!bootstrapValidator.isValid()) {
        return;
    }
    $.ajax({
        url: '/csd/productManager/exchangeApproval',
        type: 'POST',
        dataType: "json",
        data: {
            changeCourseId:changeCourseId,
            remarks:$.trim($("#remarks").val()),
            examine:$("input[name='approvalResult']:checked").val(),
            ruleTitle:$("#ruleTitleText").text(),
            courseId:changeCourseTypeNum!=2?'':getStr(exchangeTableData,'changeCourseId'),
            changeCourseTitle:changeCourseTypeNum!=2?'':getStr(exchangeTableData,'changeCourseTitle')
        },
        success: (function (data) {
            if (data.code == '000000') {
                if(data.data.code==0){
                    $.alert("审批成功");
                    $("#approvalModal").modal('hide');
                    exchangeDetailsList();
                } else if(data.data.code == '1'){
                    $.alert(data.data.msg);
                }

            }
        }),
        error: (function () {
            $.alert("请求失败");
        })
    })


}


/**
 * 点击合同编号跳转到合同详情
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function contractNumberFormat(value, row, index) {
    if(value == null) {
        value = '';
    }
    return '<a href="JavaScript:void(0);"   onclick=\'contractNumberDetail(\"'+row.contractId+'")\'>'+value+'</a>';
}
function  contractNumberDetail(contractId) {
    if(contractId == null || contractId == '') {
        $.alert("合同信息有误!");
        return;
    }
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '合同详情',
        url : "/front/contractManager/contractDetail?contractId=" + contractId
    }, true);
}


/**
 * 点击会员卡卡号跳转到会员卡详情
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function customerCardDetail(value, row, index) {
    if(value == null) {
        value = '';
    }
    return '<a href="JavaScript:void(0);"   onclick=\'customerCardDetaila(\"'+row.customerProductDetailMemberCardId+'",\"'+row.memberCardNumber+'")\'>'+value+'</a>';
}
function  customerCardDetaila(customerProductDetailMemberCardId,memberCardNumber) {
    if(customerProductDetailMemberCardId == null || customerProductDetailMemberCardId == '') {
        $.alert("会员卡信息有误!");
        return;
    }
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '会员卡详情',
        url: "/front/csd/customerManager/customerCardDetail?customerProductDetailMemberCardId=" + customerProductDetailMemberCardId + "&memberCardNumber=" + memberCardNumber
    }, true);
}


/**
 * 点击订单编号跳转到订单详情
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function orderNumberFormat(value, row, index) {
    if(value == null) {
        value = '';
    }
    return '<a href="JavaScript:void(0);" onclick="orderNumberDetail(\''+row.productOrderId+ '\',\'' + row.contractId + '\')">'+value+'</a>';
}

function  orderNumberDetail(productOrderId,contractId) {
    if(productOrderId == null || productOrderId == '') {
        $.alert("订单信息有误!");
        return;
    }
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '订单详情',
        url : "/front/orderManager/orderDetail?productOrderId=" + productOrderId+"&contractId="+ contractId
    }, true);
}